-- UIArtifactCompound
-- Create by zouyb
-- 神器合成界面

require "game/ui/form/artifact/UIArtifactEffect"
-- UIArtifactCompound继承自Layer
UIArtifactCompound = class("UIArtifactCompound", function()
    return cc.Layer:create();
end);

function UIArtifactCompound.create(classId, type)
    return UIArtifactCompound.new(classId, type);
end

-- 内部函数声明
local resize;

-- 构造函数
function UIArtifactCompound:ctor(classId, type)
    -- 初始化
    self:setName("UIArtifactCompound");
    local node = cc.CSLoader:createNode("layout/artifactt/ArtifactUpgrade.csb");
    self:addChild(node);
    self.node = node;
    self.classId = classId;

    -- 注册事件处理回调函数
    self:registerEventCallback()

    self.type = type;

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘
function UIArtifactCompound:redraw()
    local id = self.classId;
    local node = self.node;
    local CT   = node:getChildByName("CT");
    local BT   = node:getChildByName("BT");
    local funcDescLabel = findChildByName(CT, "func_desc");

        -- 显示标题
    local nameLabel = findChildByName(node, "CT/name");
    TextStyleM.setTitleStyle(nameLabel);
    local artifactName = ItemM.query(self.classId, "name")
    nameLabel:setString(artifactName);

    -- 获取当前碎片、需求碎片、需求金币数
    local level = ArtifactM.getArtifactLevel(id);
    local scrapId = 0;
    local curScrapNum = 0;
    local needScrapNum = 0;
    local needMoneyNum = 0;
    local cost = FormulaM.invoke("CALC_ARTIFACT_UPGRADE_LEVEL_COST", level + 1, id);
    for _, arr in pairs(cost) do
        if arr[1] == 1 then
            curScrapNum = ItemM.getAmount(ME.user, arr[2]); -- 碎片数
            needScrapNum = arr[3];
            scrapId = arr[2];
        elseif arr[1] == 2 then
            needMoneyNum = arr[3];
        end
    end

     -- 显示碎片个数
    local scrapNumLabel = findChildByName(CT, "scrap_num");
    TextStyleM.setSubheadStyle(scrapNumLabel);
    scrapNumLabel:setString(string.format(getLocStr("artifact_scrap_num"), curScrapNum));

        -- 图标和等级
    local function initIconAndLevel(index, lv)
        local bg = findChildByName(CT, "artifact"..index.."/bg");
        -- local rank = ItemM.query(id, "rank");
        bg:loadTexture(getFrameBgIconPath("rank_large" .. 1));

        local iconImg = findChildByName(CT, "artifact"..index.."/icon");
        local fileName;
        if lv == -1 then
            fileName = ItemM.query(scrapId, "icon");
        else
            fileName = ItemM.query(id, "icon");
        end

        iconImg:loadTexture(getItemIconPath(fileName));

        local levelBg = findChildByName(CT, "artifact"..index.."/level_bg");
        levelBg:setVisible(false);



        local starNode = findChildByName(CT, "artifact".. index .. "/sinker_panel")
        starNode:setVisible(false);

        if lv == -1 then
            local levelLabel = findChildByName(CT, "artifact"..index.."/level");
            TextStyleM.setTextStyle(levelLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
            levelLabel:setString(tostring(needScrapNum));
            levelLabel:setVisible(true);
        end
    end
    initIconAndLevel(1, level);
    initIconAndLevel(2, level + 1);

    -- 获取神器的描述
    local props = EquipM.query(id, "prop");
    local desc = EquipM.getEquipPropDesc(props);

    -- 神器属性描述
    local propLabel = findChildByName(CT, "prop");
    local kerning = -3;

    if getLang() ~= "zh" and getLang() ~= "tw" then
        kerning = -1;
    end

    TextStyleM.setTextStyle(propLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE, false);
    propLabel:getVirtualRenderer():setAdditionalKerning(kerning);
    propLabel:setString(string.format(getLocStr("artifact_compound_tip"), artifactName, desc));

    -- 消耗
    local costLabel = findChildByName(CT, "cost");
    TextStyleM.setTextStyle(costLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false);

    local moneyCount = ME.user:queryAttrib("money");
    local costStr = getLocStr("artifact_compound_cost");
    local scrapColor = "[blue]%d[-]";
    local moneyColor = "[blue]%d[-]";
    local ret = ArtifactM.canCompound(self.classId);
    if ret ~= true then
        local btnOk = findChildByName(node, "CT/btn_ok");
        btnOk:setBright(false);
        btnOk:setTouchEnabled(false);

        -- 获取该等级升级的消耗
        local cost = ArtifactM.getUpgradeCost(self.classId);
        for _, arr in pairs(cost) do
            if arr[1] == 1 then
                if ItemM.getAmount(ME.user, arr[2]) < arr[3] then
                    scrapColor = "[red]%d[-]";
                end
            elseif arr[1] == 2 then
                if ME.user:queryAttrib(arr[2]) < arr[3] then
                    moneyColor = "[red]%d[-]";
                end
            end
        end
    end
    local str =  string.format(costStr, scrapColor, moneyColor);
    applyString(costLabel, string.format(str, needScrapNum, needMoneyNum));
end

-- 注册事件处理回调函数
function UIArtifactCompound:registerEventCallback()

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            EventMgr.removeAll("UIArtifactCompound");
            if self.type == 1 then
               local topMenu = UIMgr:getCurrentScene().topMenu;
               if topMenu then
                   topMenu:setLocalZOrder(UIMgr.TOP_MENU_ZORDER);
               end
            end
        elseif ev == "enter" then

        end
    end);

    -- 关注修复成功的事件
    EventMgr.register("UIArtifactCompound", event.ARTIFACT_COMPOUND, function(args)

        local uiArtiafactEffect;
        if self.type == 1 then
            uiArtiafactEffect = UIArtifactEffect.create(self.classId, "compound");
        else
            uiArtiafactEffect = UIArtifactEffect.create(self.classId, "compound");
        end
        UIMgr.getCurrentScene():addForm(uiArtiafactEffect);

        UIMgr.getCurrentScene():removeFormByName("UIArtifactCompound");
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIArtifactCompound", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIArtifactCompound" then
            if self.type == 1 then
                self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);
                UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
                UIMgr:getCurrentScene().topMenu:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 2);
            end
        end
    end);

end

-- 注册点击事件
function UIArtifactCompound:registerTouchEvent()
    local node = self.node;

    local itemBtn = findChildByName(node, "CT/info/item/bg");

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIArtifactCompound");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册确认按钮点击事件
    local btnOk = findChildByName(node, "CT/btn_ok");
    local function onOKClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 客户端预判是否可以合成
            local ret = ArtifactM.canCompound(self.classId);
            if ret ~= true then
                alert(getLocStr(ret));
                return;
            end

            -- 向服务器发送神器合成请求
            Operation.cmd_compound_artifact(self.classId);
        end
    end

    btnOk:addTouchEventListener(onOKClick);
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);

    btnOk:setTitleText(getLocStr("btn_text_compound"));
end

-- 显示神器详细界面
function UIArtifactCompound:showDetailInfo(id, type)
    self.isLongPress = true;

    local uiItemDesc = UIEquipTooltip.create(id, type);
    UIMgr:getCurrentScene():addForm(uiItemDesc);
end
